package com.yunfeisoft.business.controller;

import com.yunfeisoft.common.base.BaseController;
import com.yunfeisoft.common.session.WebDomainContext;
import com.yunfeisoft.common.utils.AjaxUtils;
import com.yunfeisoft.common.utils.CookieHelper;
import com.yunfeisoft.common.weixin.WXOpenApi;
import com.yunfeisoft.common.weixin.model.WXOpenId;
import com.yunfeisoft.utils.ApiUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author Administrator
 */
@Controller
public class CallBackController extends BaseController {

    @Autowired
    private WebDomainContext webDomainContext;
    @Autowired
    private WXOpenApi wxOpenApi;
    /*@Autowired
    private ThreadPoolManager threadPoolManager;*/
    /*@Value("${wx.token}")
    private String token;*/

    private final static Object LOCK = new Object();


    /**
     * 微信页面跳转回调
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/callback/{page}", method = {RequestMethod.POST, RequestMethod.GET})
    public String index(@PathVariable("page") String page, HttpServletRequest request, HttpServletResponse response) {
        String code = ServletRequestUtils.getStringParameter(request, "code", null);
        log.info("code = " + code);
        if (StringUtils.isEmpty(code)) {
            AjaxUtils.ajaxText("微信授权错误");
            return null;
        }

        //String openId = code;
        WXOpenId wxOpenId = wxOpenApi.getOpenId(code);
        if (wxOpenId == null || StringUtils.isEmpty(wxOpenId.getOpenid())) {
            AjaxUtils.ajaxText("微信授权异常");
            return null;
        }

        String openId = wxOpenId.getOpenid();
        CookieHelper.setCookie(response, ApiUtils.WX_TOKEN_COOKIE_NAME, openId);
        //threadPoolManager.executeTask(new SaveWeixinUser(openId, null));

        return String.format("redirect:%s/view/business/mobile/%s.htm?_t=%d", webDomainContext.getWebDomain(), page, new Date().getTime());
    }

    /*private class SaveWeixinUser implements Runnable {

        private String openId;
        private String sceneNo;//场景编码

        public SaveWeixinUser(String openId, String sceneNo) {
            this.openId = openId;
            this.sceneNo = sceneNo;
        }

        @Override
        public void run() {
            synchronized (LOCK) {
                if (StringUtils.isEmpty(openId)) {
                    return;
                }
                WeixinUser weixinUser = weixinUserService.loadByOpenId(openId);
                if (weixinUser != null) {
                    saveFriend(weixinUser, sceneNo, false);
                    return;
                }
                WXUser wxUser = wxOpenApi.getUser(openId);

                weixinUser = new WeixinUser();
                weixinUser.setId(KeyUtils.getKey());
                weixinUser.setOpenid(openId);
                weixinUser.setAmount(BigDecimal.ZERO);
                //weixinUser.setLockAmount(BigDecimal.ZERO);
                if (wxUser != null) {
                    String[] sexArray = new String[]{"未知", "男", "女"};
                    weixinUser.setNickName(wxUser.getNickname());
                    weixinUser.setGender(sexArray[wxUser.getSex()]);
                    weixinUser.setHeadPhoto(wxUser.getHeadimgurl());
                    *//*if (wxUser.getSubscribe_time() > 0) {//关注时间
                        String str = String.valueOf(wxUser.getSubscribe_time()) + "000";
                        weixinUser.setAttentTime(new Date(Long.valueOf(str)));
                    }*//*
                }

                saveFriend(weixinUser, sceneNo, true);
                weixinUserService.save(weixinUser);
            }
        }
    }*/

    /**
     * 保存收徒信息
     * @param weixinUser
     * @param parentUserId
     * @param isSaveUser
     */
    /*private void saveFriend(WeixinUser weixinUser, String parentUserId, boolean isSaveUser) {
        if (StringUtils.isBlank(parentUserId) || parentUserId.equals(weixinUser.getId())) {
            log.info("parentUserId = " + parentUserId + " weixinUser.getId() = " + weixinUser.getId());
            return;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("friendId", weixinUser.getId());
        params.put("weixinUserId", parentUserId);
        int count = friendService.count(params);
        if (count > 0) {
            return;
        }

        Friend friend = new Friend();
        friend.setFriendId(weixinUser.getId());
        friend.setWeixinUserId(parentUserId);
        if (isSaveUser) {
            weixinUser.setFriend(friend);
            return;
        }
        friendService.save(friend);
    }*/

    /*private void signature(HttpServletRequest request, HttpServletResponse response) {
        String signature = ServletRequestUtils.getStringParameter(request, "signature", null);
        String timestamp = ServletRequestUtils.getStringParameter(request, "timestamp", null);
        String nonce = ServletRequestUtils.getStringParameter(request, "nonce", null);
        String echostr = ServletRequestUtils.getStringParameter(request, "echostr", null);

        List<String> array = new ArrayList<String>();
        array.add(signature);
        array.add(timestamp);
        array.add(nonce);

        //排序
        String sortString = sort(token, timestamp, nonce);
        //加密
        String mytoken = SHA1Utils.encode(sortString);
        //校验签名
        if (StringUtils.isNotEmpty(mytoken) && mytoken.equals(signature)) {
            log.info("签名校验通过。");
            AjaxUtils.ajaxText(echostr); //如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
        } else {
            log.info("签名校验失败。");
        }
    }*/

    /**
     * 排序方法
     *
     * @param token
     * @param timestamp
     * @param nonce
     * @return
     */
    /*public String sort(String token, String timestamp, String nonce) {
        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);

        StringBuilder sbuilder = new StringBuilder();
        for (String str : strArray) {
            sbuilder.append(str);
        }

        return sbuilder.toString();
    }*/

    /**
     * 微信推送回调事件接口
     *
     * @param request
     * @param response
     * @return
     */
    /*@RequestMapping(value = "/push/callback", method = {RequestMethod.POST, RequestMethod.GET})
    public void push(HttpServletRequest request, HttpServletResponse response) {
        String echostr = ServletRequestUtils.getStringParameter(request, "echostr", null);
        if (StringUtils.isNotEmpty(echostr)) {
            signature(request, response);
            return;
        }
        WXmlHelper wXmlHelper = new WXmlHelper(request);
        WXAcceptEventMessage wxAcceptEventMessage = wXmlHelper.getWxAcceptSubscribeEventMessage();
        if (wxAcceptEventMessage != null) {
            eventMessage(wxAcceptEventMessage);
            WXReplyTextMessage wxReplyTextMessage = new WXReplyTextMessage();
            wxReplyTextMessage.setToUserName(wxAcceptEventMessage.getFromUserName());
            wxReplyTextMessage.setFromUserName(wxAcceptEventMessage.getToUserName());
            wxReplyTextMessage.setCreateTime(String.valueOf(new Date().getTime() / 1000));
            wxReplyTextMessage.setContent("众推邦致力于为用户提供真实，快速，零投入，零风险，可靠的手机赚钱项目！不收取任何费用，让用户在闲暇时间用一部手机就可以得到一份额外的收入，动动手指，即可赚钱！同时，帮助商户做好宣传和推广，更好的打入市场！\n\n" +
                    "客服微信:ZTBKEFU\n" +
                    "客服QQ:2660319621\n" +
                    "遇到问题及时联系客服，客服看到后会及时回答。");
            //System.out.println("reply : " + wxReplyTextMessage.getMessage());
            AjaxUtils.ajaxText(wxReplyTextMessage.getMessage());
            return;
        }

        AjaxUtils.ajaxText("success");
    }*/

    //扫描带参数二维码事件，关注/取消关注事件 接收消息
    /*public void eventMessage(WXAcceptEventMessage wxAcceptEventMessage) {
        String sceneNo = null;
        if (StringUtils.isNotEmpty(wxAcceptEventMessage.getEventKey())) {
            sceneNo = wxAcceptEventMessage.getEventKey().replaceFirst("qrscene_", "");
        }
        SaveWeixinUser saveWeixinUser = new SaveWeixinUser(wxAcceptEventMessage.getFromUserName(), sceneNo);
        saveWeixinUser.run();
    }*/
}
